﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace homework8_h2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodosController : ControllerBase
    {
        private readonly List<TodoItem> _todoItems = new();
        private int _nextId = 1;

        // GET: api/todos
        [HttpGet]
        public ActionResult<IEnumerable<TodoItem>> GetAll()
        {
            return Ok(_todoItems);
        }

        // GET: api/todos/5
        [HttpGet("{id}")]
        public ActionResult<TodoItem> GetById(int id)
        {
            var item = _todoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
            {
                return NotFound();
            }
            return Ok(item);
        }

        // POST: api/todos
        [HttpPost]
        public ActionResult<TodoItem> Create([FromBody] TodoItem item)
        {
            item.Id = _nextId++;
            item.CreatedAt = DateTime.Now;
            _todoItems.Add(item);

            return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
        }

        // PUT: api/todos/5
        [HttpPut("{id}")]
        public IActionResult Update(int id, [FromBody] TodoItem item)
        {
            var existingItem = _todoItems.FirstOrDefault(t => t.Id == id);
            if (existingItem == null)
            {
                return NotFound();
            }

            existingItem.Title = item.Title;
            existingItem.Description = item.Description;
            existingItem.IsCompleted = item.IsCompleted;
            existingItem.DueDate = item.DueDate;

            return NoContent();
        }

        // DELETE: api/todos/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var item = _todoItems.FirstOrDefault(t => t.Id == id);
            if (item == null)
            {
                return NotFound();
            }

            _todoItems.Remove(item);
            return NoContent();
        }
    }
}
